package com.module.ad.toutiao;

import android.view.View;

import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.module.privacy.module_ad.LogADUtils;

import java.util.List;

/**
 * 插屏广告
 */
public class TTChaPingAd {

    private static TTNativeExpressAd mTTAd;
    private static final String TAG = "头条广告";

    public static void loadAd(FragmentActivity context, String posId) {
        LogADUtils.d(TAG, "启动头条插屏广告");
        TTAdNative mTTAdNative = TTAdManagerHolder.get().createAdNative(context);
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(posId) //广告位id
                .setSupportDeepLink(true)
                .setAdCount(1) //请求广告数量为1到3条
                .setExpressViewAcceptedSize(300, 300) //期望模板广告view的size,单位dp
                .build();
        mTTAdNative.loadInteractionExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
            //请求广告失败
            @Override
            public void onError(int code, String message) {
                LogADUtils.d(TAG, "头条插屏广告错误：" + message);

            }

            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> list) {
                if (list == null || list.size() == 0) {
                    return;
                }
                LogADUtils.d(TAG, "头条插屏广告成功");
                mTTAd = list.get(0);
                mTTAd.setSlideIntervalTime(30 * 1000);
                mTTAd.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {
                    @Override
                    public void onAdClicked(View view, int i) {

                    }

                    @Override
                    public void onAdShow(View view, int i) {

                    }

                    @Override
                    public void onRenderFail(View view, String s, int i) {

                    }

                    @Override
                    public void onRenderSuccess(View view, float v, float v1) {
                        mTTAd.showInteractionExpressAd(context);

                    }
                });
                mTTAd.render();
            }

        });
        context.getLifecycle().addObserver(new LifecycleObserver() {
            @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
            public void onDestroy() {
                //取消广告
                if (mTTAd != null) {
                    mTTAd.destroy();
                    mTTAd = null;
                }
            }

        });
    }

}
